<?php

namespace app\controllers\h5\services;

use app\models\order\Order;
use app\models\system\SetApp;
use app\models\user\User as Model;
use app\services\Chain;

/**
 * Class User
 * @package app\controllers\h5\services
 */
class User extends \app\services\User
{
    /**
     * Login
     *
     * @param $mobile
     * @param $password
     * @return array|\yii\db\ActiveRecord|null
     */
    public static function login($mobile, $password)
    {
        return Model::find()
            ->where(['mobile' => $mobile, 'password' => $password])
            ->andWhere(['!=', 'status', Model::$statusMapping['DELETE']])
            ->one();
    }

    /**
     * Get user info
     *
     * @param $id
     * @return array|\yii\db\ActiveRecord|null
     */
    public static function getInfo($id)
    {
        $model = Model::find()
            ->where(['id' => $id])
            ->with(['level0', 'level2', 'referrer', 'account', 'merchant', 'groupLevel0'])
            ->asArray()
            ->one();

        // nickname
        $model['nickname'] = base64_decode($model['nickname']);

        // order count
        $order = [
            'non_payment' => Order::find()
                ->where(['user_id' => $id])
                ->andWhere(['status' => Order::$statusMapping['NON_PAYMENT']])
                ->count(),
            'paid' => Order::find()
                ->where(['user_id' => $id])
                ->andWhere(['status' => Order::$statusMapping['PAID']])
                ->count(),
            'wait_receiving' => Order::find()
                ->where(['user_id' => $id])
                ->andWhere(['status' => Order::$statusMapping['WAIT_RECEIVING']])
                ->count(),
            'received' => Order::find()
                ->where(['user_id' => $id])
                ->andWhere(['status' => Order::$statusMapping['FINISH']])
                ->count(),
            'service' => Order::find()
                ->where(['user_id' => $id])
                ->andWhere(['status' => Order::$statusMapping['SERVICE']])
                ->count(),
        ];

        $model['order_count'] = $order;

        unset($model['password']);

        // order & team
        $model['order'] = Order::find()
            ->where(['user_id' => $id])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->count();

        // team
        $children = Chain::getChildrenAll($id);
        $model['team'] = count($children);

        // 是否开启互转
        $set = SetApp::getLastOne();
        $model['open_transfer'] = $set->open_transfer == 1;

        return $model;
    }
}